﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Text;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace DevUIUtils
{
    /// <summary>
    /// 字体图标帮助扩展类
    /// </summary>
    public static class IconFontHelper
    {
        private static PrivateFontCollection _PFC = new PrivateFontCollection();

        /// <summary>
        /// 加载图标字体(文件)
        /// </summary>
        /// <param name="ctl">控件对象</param>
        /// <param name="fontFile">图标字体文件</param>
        public static void LoadIconFont(this Control ctl, string fontFile)
        {
            _PFC.AddFontFile(fontFile);
            ctl.Font = new Font(_PFC.Families.FirstOrDefault(t => t.Name == "iconfont"), 9);
        }

        /// <summary>
        /// 加载图标字体(内存字节，如Resources.iconfont)
        /// </summary>
        /// <param name="ctl"></param>
        /// <param name="fontData"></param>
        public static void LoadIconFont(this Control ctl, byte[] fontData)
        {
            IntPtr fontHandle = Marshal.UnsafeAddrOfPinnedArrayElement(fontData, 0);
            _PFC.AddMemoryFont(fontHandle, fontData.Length);
            ctl.Font = new Font(_PFC.Families.FirstOrDefault(t => t.Name == "iconfont"), 9);
        }

        /// <summary>
        /// Iconfont官网Unicode编码转显示字符串
        /// </summary>
        /// <param name="iconCodes">Iconfont官网Unicode编码，可以为多个图标连接</param>
        /// <returns></returns>
        public static string IconFontCodesToString(string iconCodes)
        {
            List<string> charCodes = iconCodes.Replace("&#x", "").Split(';').ToList();
            charCodes.RemoveAll(x => string.IsNullOrWhiteSpace(x));
            StringBuilder sb = new StringBuilder();
            foreach (var charCode in charCodes)
            {
                sb.Append((char)Convert.ToInt16(charCode, 16));
            }
            return sb.ToString();
        }

    }
}
